package feishu;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SignDemo {

	public static String GenSign(String secret, long timestamp) {
		// 把timestamp+"\n"+密钥当做签名字符串
		String stringToSign = timestamp + "\n" + secret;
		// 使用HmacSHA256算法计算签名
		Mac mac = null;
		try {
			mac = Mac.getInstance("HmacSHA256");
			mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		} catch (InvalidKeyException e) {
			throw new RuntimeException(e);
		}
		byte[] signData = mac.doFinal(new byte[] {});
		return new String(Base64.getEncoder().encode(signData));
	}

	public static void main(String[] args) throws JsonProcessingException {
		Map<String, String> msg = new LinkedHashMap<>();
		msg.put("票据不存在监控", "");
		msg.put("地区: ", "湖北");
		msg.put("时间段: ", "YYYY-MM-DD HH:mm ~ HH:mm  ");
		msg.put("总核验量: ", "150张");
		msg.put("票据不存在占比: ", "8%");
		msg.put("请关注“票据不存在”是否为财政升级导致，及时适配。", "");
		sendmsg(msg);
	}

	public static void sendmsg(Map<String, String> msg) {

		StringBuilder sb = new StringBuilder();
		msg.forEach((k, v) -> {
			sb.append(k).append(v).append("\r\n");
		});
		sb.append("<at user_id = 'all'>所有人</at>").append("\r\n");

		Map<String, Object> text = new HashMap<>();
		text.put("text", sb.toString());
		Map<String, Object> json = new HashMap<>();
		json.put("msg_type", "text");
		json.put("content", text);

		long timeMillis = System.currentTimeMillis();
		json.put("timestamp", timeMillis);
		json.put("sign", GenSign("mGEOhIqeJp07EoWF68rz1fRFfEVP8S2I", timeMillis));

		ObjectMapper objectMapper = new ObjectMapper();
		try {
			String jsonStr = objectMapper.writeValueAsString(json);
			System.out.println(jsonStr);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
